﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Threading;
using System.Windows.Xps;
using System.Windows.Documents;
using System.Windows.Xps.Packaging;
using System.Windows.Documents.Serialization;
using System.Runtime.InteropServices;
//*

namespace EncircleFTM
{
    public partial class frmStatusMonitor : Form
    {
        #region "Member variables"
        private System.IO.FileSystemWatcher FolderWatcher = null;
        private string Folderpath = string.Empty;
        private System.Timers.Timer _ClearLogTimer = new System.Timers.Timer();
        private UploadDataToEncircleDelegate objUploadDataDelegate;
        private System.Collections.ArrayList ar = new System.Collections.ArrayList();
        public bool isValidUser = false;
        private bool isAdditionalInfoNeeded = true;
        private string userName = System.Environment.UserName;
              
        #endregion

        /// <summary>
        /// Used to handle log details for grid refresh
        /// </summary>
        private static clsLog objLog2 = new clsLog();

        /// <summary>
        /// Default constructor
        /// </summary>
        public frmStatusMonitor()
        {


            InitializeComponent();

            _ClearLogTimer.Elapsed += new System.Timers.ElapsedEventHandler(_ClearLogTimer_Elapsed);
            InitializeCustomMenu();
            this.Size = new Size(800, 450);
        }


        /// <summary>
        /// Used to Initialize the watching folder
        /// </summary>
        /// <param name="folderPath"></param>
        public bool InitFolderWatcher(string folderPath)
        {
            bool retVal = false;
            if (new DirectoryInfo(folderPath).Exists)
            {
                if (FolderWatcher != null)
                {
                    FolderWatcher.Dispose();
                    FolderWatcher = null;
                }

                FolderWatcher = new System.IO.FileSystemWatcher(clsSettings.FolderPath + "\\" + userName, "*.xps");
                FolderWatcher.Created += new FileSystemEventHandler(FolderWatcher_Created);
                FolderWatcher.NotifyFilter =
                   (NotifyFilters.LastAccess |
                    NotifyFilters.LastWrite |
                    NotifyFilters.FileName |
                    NotifyFilters.DirectoryName);
                retVal = true;
            }
            return retVal;
        }




        public delegate void UpdateStatusDelegate2(string msg);
        public void UpdateStatus2(string msg)
        {
            lblStatus.Text = msg;
        }


        /// <summary>
        /// Used to hide the screen after application get started
        /// </summary>
        /// <param name="e"></param>
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            this.Hide();
        }

        /// <summary>
        /// Automatic Clear Log handler 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void _ClearLogTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //Call clear log functionality
        }

        /// <summary>
        /// Used to load log details in grid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmStatusMonitor_Load(object sender, EventArgs e)
        {
            //Runtime Control size changes
            lblStatus.Width = this.ClientRectangle.Width - 20;
            this.Update();

            if (!clsSettings.IsConfigFileExists)
            {
                //move default configuration to application folder
                string appPath = clsCommonData.APP_PATH;
                string appDataPath = clsCommonData.APP_DATA_PATH;
                string sourcePath = System.IO.Path.Combine(appPath, "prerequisites\\Config.xml");
                string destinationPath = System.IO.Path.Combine(appDataPath, "Config.xml");
                if (File.Exists(sourcePath))
                {
                    StreamReader reader = new System.IO.StreamReader(sourcePath);
                    string strDefaultFileContent = reader.ReadToEnd();
                    reader.Close();
                    reader = null;
                    StreamWriter writer = new System.IO.StreamWriter(destinationPath);
                    writer.Write(strDefaultFileContent);
                    writer.Close();
                    writer = null;
                    clsSettings.ReadSettings();
                }

                MessageBox.Show(string.Format("{0},{1}", clsCommonData.MSG_FAILURE, clsCommonData.MSG_REENTER_SETTINGS), clsCommonData.STR_APPNAME);
                lblStatus.Text = clsCommonData.MSG_FAILURE;
                smFileSettings_Click(btnSettings, null);
                return;
            }
            else
            {
                lblStatus.Text = clsSettings.GetAppPath();

                //Start folder watcher functionality
                StartFolderWathcher();

                //Load status list view control
                LoadStatusList();
            }
        }

        /// <summary>
        /// Used load status list view control data
        /// </summary>
        private void LoadStatusList()
        {
            try
            {
                // Read XML DAta or Deserialize xml data with Entity class
                objLog2 = clsCommonData.ReadLogData();   //Validate log data

                if (objLog2 == null) lblStatus.Text = "No log details found.";
                if (!((objLog2.lstLogData != null) && objLog2.lstLogData.Count > 0)) lblStatus.Text = "No log details found.";

                //Parse log details and add in list view control
                lstLogsuccess.Invoke(new RefreshListViewDelegate(RefreshListMethod), new object[] { objLog2.lstLogData.ToArray(), clsCommonData.STR_SUCCESS });
            }
            catch (Exception ex)
            {
                clsCommonData.WriteError(ex.ToString());
            }
        }

        /// <summary>
        /// Used to refresh log list view control
        /// </summary>
        private delegate void RefreshListViewDelegate(LogData[] logData, string status);
        private void RefreshListMethod(LogData[] logData, string status)
        {
            try
            {
                if (logData == null)
                {
                    lblStatus.Text = "No file transfer log data found.";
                    return;
                }

                if (logData.Length > 0)
                {
                    lstLogsuccess.Items.Clear();
                    lstLogFailed.Items.Clear();
                    lvInProgress.Items.Clear();
                }
                int snoSuccess = 0;
                int snoFailed = 0;
                int index = 0;
                foreach (LogData logdata in logData)
                {
                    ListViewItem lvLogData = new ListViewItem();
                    lvLogData.SubItems.Add(logdata.FileName);
                    lvLogData.SubItems.Add(logdata.Status);
                    lvLogData.SubItems.Add(logdata.Remark);
                    lvLogData.SubItems.Add(index.ToString());
                    index++;

                    if (logdata.Status.ToUpper() == clsCommonData.STR_SUCCESS)
                    {
                        snoSuccess++;
                        lvLogData.Text = snoSuccess.ToString();
                        lstLogsuccess.Items.Add(lvLogData);
                    }
                    else
                    {
                        snoFailed++;
                        lvLogData.Text = snoFailed.ToString();
                        lstLogFailed.Items.Add(lvLogData);
                    }
                }
                if (logData.Length > 0)
                {
                    if (status == clsCommonData.STR_SUCCESS && lstLogsuccess.Items.Count > 0)
                    {
                        int count = lstLogsuccess.Items.Count - 1;
                        lstLogsuccess.Items[count].Selected = true;
                        lstLogsuccess.Items[count].Focused = true;
                        lstLogsuccess.Items[count].EnsureVisible();
                        lstLogsuccess.Focus();
                        btnSuccess_Click(null, null);
                        //tabpage.SelectedIndex = 1;
                        this.Update();
                    }
                    else if (status == clsCommonData.STR_FAILED && lstLogFailed.Items.Count > 0)
                    {
                        int count = lstLogFailed.Items.Count - 1;
                        lstLogFailed.Items[count].Selected = true;
                        lstLogFailed.Items[count].Focused = true;
                        lstLogFailed.Items[count].EnsureVisible();
                        lstLogFailed.Focus();
                        btnFailed_Click(null, null);
                        //tpgFailed.Focus();
                        //tabpage.SelectedIndex = 2;
                        this.Update();
                    }
                }
            }
            catch (Exception ex)
            {
                //clsCommonData.WriteError(ex.Message);
            }
        }

        /// <summary>
        /// Used to handle XPS file created in watching folder
        /// </summary>
        /// <returns></returns>
        public bool StartFolderWathcher()
        {
            try
            {

                String path = clsSettings.FolderPath + "\\" +  userName;
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                if (!System.IO.Directory.Exists(path))
                {
                    lblStatus.Text = "Please check the folder settings.";
                    return false;
                }

                if (InitFolderWatcher(path))
                {
                    FolderWatcher.EnableRaisingEvents = true;
                    lblStatus.Text = "Folder Monitor started...";
                }
                else
                {
                    lblStatus.Text = "Please check the folder settings.";
                }
            }
            catch (Exception ex)
            {
                clsCommonData.WriteError(ex.ToString());
            }
            return true;
        }

        /// <summary>
        /// Used to stop folder watcher
        /// </summary>
        /// <returns></returns>
        public bool StopFolderWathcher()
        {
            try
            {
                if (FolderWatcher != null)
                {
                    FolderWatcher.EnableRaisingEvents = false;
                }
                lblStatus.Text = "Folder Monitor Stopped.";
            }
            catch (Exception ex)
            {
                clsCommonData.WriteError(ex.ToString());
            }
            return true;
        }

        #region "Upload data"
        public delegate EncircleFileUpload.UploadStatus UploadDataToEncircleDelegate(
            string pFullPath, string pFileName, int logTotal, int selItemIndex, bool isResend, byte[] xpsData);
        public EncircleFileUpload.UploadStatus UploadDataToEncircleMethod(
            string pFullPath, string pFileName, int logTotal, int selItemIndex, bool isResend, byte[] xpsData)
        {
            //EncircleDataUpload.UploadStatus objEncircleUploadStatus = new EncircleFTM.EncircleDataUpload.UploadStatus();
            //EncircleDataUpload.Service objEncircleService;

            EncircleFileUpload.UploadStatus objEncircleUploadStatus =
                new EncircleFTM.EncircleFileUpload.UploadStatus();
            EncircleFileUpload.Service objEncircleService;

            string xmlData = string.Empty;
            string CompanyName = clsSettings.CompanyName;
            string CompanyUniqueID = clsSettings.UniqueID;
            string ReferenceName = pFileName;
            string tempFileName = string.Empty;
            string newXMLFileName = string.Empty;
            string newXPsFileName = string.Empty;
            LogData objLogData = new LogData();
            string fileExt = string.Empty;

            try
            {
                //Step 1: Check created file is .xps or not
                if (!pFileName.ToUpper().EndsWith(".XPS"))
                {
                    objEncircleUploadStatus.Status = clsCommonData.STR_FAILED;
                    objEncircleUploadStatus.Message = "FILE ERROR:Invalid XPS file";
                    return objEncircleUploadStatus;
                }

                //Step 1.1: Build file names
                tempFileName = pFileName.Replace(".xps", "");
                if (isResend)
                {
                    newXMLFileName = string.Format("{0}.xml", tempFileName);
                    newXPsFileName = string.Format("{0}.xps", tempFileName);
                }
                else
                {
                    newXMLFileName = string.Format("{0}_{1}_{2}.xml", CompanyName, CompanyUniqueID, tempFileName);
                    newXPsFileName = string.Format("{0}_{1}_{2}.xps", CompanyName, CompanyUniqueID, tempFileName);
                }

                //Step 3: Read xPS's file XML content using XPSDocument class var: xpsXmlData: string
                xmlData = readXPSDocument(pFullPath);

                if (string.IsNullOrEmpty(xmlData))
                {
                    objEncircleUploadStatus.Status = clsCommonData.STR_FAILED;
                    objEncircleUploadStatus.Message = "Invalid XPS file";
                    return objEncircleUploadStatus;
                }

                fileExt = System.IO.Path.GetExtension(pFullPath);
                ReferenceName = ReferenceName.Replace(fileExt, string.Empty);

                //Step 4: create instance of EncricleDAtaupload webservice
                objEncircleService = new EncircleFTM.EncircleFileUpload.Service();
                objEncircleService.Url = clsSettings.UploadURL;

                //Step 5: create instance of Encircle Upload Status class
                objEncircleUploadStatus = new EncircleFTM.EncircleFileUpload.UploadStatus();


                //Step 6: Call "UploadDAta" method and get return value to UploadStatus object
                ntfStatusMonitor.BalloonTipTitle = "ECHO";
                ntfStatusMonitor.BalloonTipText = "File Uploading..";
                ntfStatusMonitor.ShowBalloonTip(1000);
                Application.DoEvents();
                byte[] xmlDataByteArr = System.Text.Encoding.ASCII.GetBytes(xmlData);
                objEncircleUploadStatus = (EncircleFTM.EncircleFileUpload.UploadStatus)
                    objEncircleService.UploadData(xpsData, xmlDataByteArr, CompanyName, CompanyUniqueID, ReferenceName);


                //Step 7: validate uploadstatus success/failure
                if (objEncircleUploadStatus.Status.ToUpper() == clsCommonData.STR_SUCCESS)
                {
                    if (!isResend)
                    {
                        //Step 7: In success case
                        //Step 7.1: create XML file in "Log/Success" folder using the content which is read in step 3
                        string xmlfilePath = System.IO.Path.Combine(clsCommonData.APP_DATA_PATH,
                            clsCommonData.STR_FOLDER_LOG_SUCCESS + "\\" + newXMLFileName);

                        if (File.Exists(xmlfilePath)) File.Delete(xmlfilePath);
                        StreamWriter writer = new StreamWriter(xmlfilePath);

                        writer.Write(xmlData);
                        writer.Close();
                        writer = null;


                        //Step 7.2: Move XPs file created in watching folder to application log folder "Log/Success"
                        string destinationFolderPath = System.IO.Path.Combine(clsCommonData.APP_DATA_PATH,
                            clsCommonData.STR_FOLDER_LOG_SUCCESS + "\\" + newXPsFileName);
                        if (File.Exists(destinationFolderPath)) File.Delete(destinationFolderPath);
                        if (File.Exists(pFullPath))
                        {
                            System.IO.File.Move(pFullPath, destinationFolderPath);
                        }
                    }
                }
                else
                {
                    if (!isResend)
                    {
                        //Step 8: In failure case
                        //Step 8.1: create XML file in "Log/Failed" folder using the content which is read in step 3
                        string xmlfilePath = System.IO.Path.Combine(clsCommonData.APP_DATA_PATH,
                            clsCommonData.STR_FOLDER_LOG_FAILED + "\\" + newXMLFileName);

                        if (File.Exists(xmlfilePath)) File.Delete(xmlfilePath);
                        StreamWriter writer = new StreamWriter(xmlfilePath);

                        writer.Write(xmlData);
                        writer.Close();
                        writer = null;


                        //Step 8.2: Move XPs file created in watching folder to application log folder "Log/Failed"
                        string destinationFolderPath = System.IO.Path.Combine(clsCommonData.APP_DATA_PATH,
                            clsCommonData.STR_FOLDER_LOG_FAILED + "\\" + newXPsFileName);
                        if (File.Exists(destinationFolderPath)) File.Delete(destinationFolderPath);
                        if (File.Exists(pFullPath))
                        {
                            System.IO.File.Move(pFullPath, destinationFolderPath);
                        }
                    }
                }

                ////Step 7.3: Create a new "LogData" node in "Log.xml" file
                if (isResend)
                {
                    if (objEncircleUploadStatus.Status.ToUpper() == "SUCCESS")
                    {
                        clsLog objLog = clsCommonData.ReadLogData();
                        if (objLog != null && objLog.lstLogData != null)
                        {
                            if (objLog.lstLogData.Count > selItemIndex)
                            {
                                LogData objLogDataUpdate = new LogData();
                                objLogDataUpdate.FileName = newXPsFileName;
                                objLogDataUpdate.Status = objEncircleUploadStatus.Status;
                                objLogDataUpdate.Remark = objEncircleUploadStatus.Message;
                                clsCommonData.writeLogData(objLogDataUpdate, selItemIndex);
                            }
                        }
                    }
                }
                else
                {
                    objLogData.FileName = newXPsFileName;
                    objLogData.SNO = Convert.ToString(logTotal + 1);
                    objLogData.Status = objEncircleUploadStatus.Status;
                    objLogData.Remark = objEncircleUploadStatus.Message;
                    clsCommonData.writeLogData(objLogData, -1);
                }
            }
            catch (Exception ex)
            {
                clsCommonData.WriteError(ex.Message);
                objEncircleUploadStatus.Status = clsCommonData.STR_FAILED;
                objEncircleUploadStatus.Message = ex.Message;

                if (!isResend)
                {
                    //Step 8: In failure case
                    //Step 8.1: create XML file in "Log/Failed" folder using the content which is read in step 3
                    string xmlfilePath = System.IO.Path.Combine(clsCommonData.APP_DATA_PATH,
                        clsCommonData.STR_FOLDER_LOG_FAILED + "\\" + newXMLFileName);

                    if (File.Exists(xmlfilePath)) File.Delete(xmlfilePath);
                    StreamWriter writer = new StreamWriter(xmlfilePath);

                    writer.Write(xmlData);
                    writer.Close();
                    writer = null;


                    //Step 8.2: Move XPs file created in watching folder to application log folder "Log/Failed"
                    string destinationFolderPath = System.IO.Path.Combine(clsCommonData.APP_DATA_PATH,
                        clsCommonData.STR_FOLDER_LOG_FAILED + "\\" + newXPsFileName);
                    if (File.Exists(destinationFolderPath)) File.Delete(destinationFolderPath);
                    if (File.Exists(pFullPath))
                    {
                        System.IO.File.Move(pFullPath, destinationFolderPath);
                    }

                    objLogData.FileName = newXPsFileName;
                    objLogData.SNO = Convert.ToString(logTotal + 1);
                    objLogData.Status = clsCommonData.STR_FAILED;
                    objLogData.Remark = ex.Message;
                    clsCommonData.writeLogData(objLogData, -1);
                }
                else
                {
                    LogData objLogDataUpdate = new LogData();
                    objLogDataUpdate.FileName = newXPsFileName;
                    objLogDataUpdate.Status = objEncircleUploadStatus.Status;
                    objLogDataUpdate.Remark = objEncircleUploadStatus.Message;
                    clsCommonData.writeLogData(objLogDataUpdate, selItemIndex);
                }
            }
            return objEncircleUploadStatus;
        }
        public String AppendAdditionalinfo()
        {
            bool readstatus = clsSettings.ReadAdditionalInfo();
            string str = "<FixedPage xml:lang='und' xmlns='http://schemas.microsoft.com/xps/2005/06' Height='1056' Width='816'> " +
                "<!-- Microsoft XPS Document Converter (MXDC) Generated! Version: 0.3.7600.16385 --><Glyphs UnicodeString='AdditionalInformation' Indices='56;81;87;76;87;79;72;71' OriginY='106.4' OriginX='376' StyleSimulations='None' FontRenderingEmSize='13.2548' FontUri='/Documents/1/Resources/Fonts/48828312-CE16-4E47-BE1C-E719758E264B.odttf' Fill='#ff000000'/>" +
          "<Glyphs UnicodeString='Patient ID: {0}' Indices='51;68;87;76;72;81;87;3;44;39;29;3;20;22;21;23;22;21' OriginY='119.68' OriginX='72' StyleSimulations='None' FontRenderingEmSize='13.2548' FontUri='/Documents/1/Resources/Fonts/48828312-CE16-4E47-BE1C-E719758E264B.odttf' Fill='#ff000000'/>" +
          "<Glyphs UnicodeString='Service date:{1}' Indices='51;68;87;76;72;81;87;3;44;39;29;3;20;22;21;23;22;21' OriginY='119.68' OriginX='72' StyleSimulations='None' FontRenderingEmSize='13.2548' FontUri='/Documents/1/Resources/Fonts/48828312-CE16-4E47-BE1C-E719758E264B.odttf' Fill='#ff000000'/>" +
          "<Glyphs UnicodeString='Document Type:{2}' Indices='51;68;87;76;72;81;87;3;44;39;29;3;20;22;21;23;22;21' OriginY='119.68' OriginX='72' StyleSimulations='None' FontRenderingEmSize='13.2548' FontUri='/Documents/1/Resources/Fonts/48828312-CE16-4E47-BE1C-E719758E264B.odttf' Fill='#ff000000'/>" +
          "<Glyphs UnicodeString='Provider: {3}' Indices='51;68;87;76;72;81;87;3;44;39;29;3;20;22;21;23;22;21' OriginY='119.68' OriginX='72' StyleSimulations='None' FontRenderingEmSize='13.2548' FontUri='/Documents/1/Resources/Fonts/48828312-CE16-4E47-BE1C-E719758E264B.odttf' Fill='#ff000000'/>" +
          "<Glyphs UnicodeString='Procedure1: {4}' Indices='51;68;87;76;72;81;87;3;44;39;29;3;20;22;21;23;22;21' OriginY='119.68' OriginX='72' StyleSimulations='None' FontRenderingEmSize='13.2548' FontUri='/Documents/1/Resources/Fonts/48828312-CE16-4E47-BE1C-E719758E264B.odttf' Fill='#ff000000'/>" +
          "<Glyphs UnicodeString='Procedure2: {5}' Indices='51;68;87;76;72;81;87;3;44;39;29;3;20;22;21;23;22;21' OriginY='119.68' OriginX='72' StyleSimulations='None' FontRenderingEmSize='13.2548' FontUri='/Documents/1/Resources/Fonts/48828312-CE16-4E47-BE1C-E719758E264B.odttf' Fill='#ff000000'/>" +
          "<Glyphs UnicodeString='Note1: {6}' Indices='51;68;87;76;72;81;87;3;44;39;29;3;20;22;21;23;22;21' OriginY='119.68' OriginX='72' StyleSimulations='None' FontRenderingEmSize='13.2548' FontUri='/Documents/1/Resources/Fonts/48828312-CE16-4E47-BE1C-E719758E264B.odttf' Fill='#ff000000'/>" +
          "<Glyphs UnicodeString='Note2: {7}' Indices='51;68;87;76;72;81;87;3;44;39;29;3;20;22;21;23;22;21' OriginY='119.68' OriginX='72' StyleSimulations='None' FontRenderingEmSize='13.2548' FontUri='/Documents/1/Resources/Fonts/48828312-CE16-4E47-BE1C-E719758E264B.odttf' Fill='#ff000000'/>" +
          "</FixedPage>";

            //     string str = "<FixedPage xml:lang='und' xmlns='http://schemas.microsoft.com/xps/2005/06' Height='1056' Width='816'> " +
            //      "<!-- Microsoft XPS Document Converter (MXDC) Generated! Version: 0.3.7600.16385 -->"+
            //      "<Glyphs UnicodeString='AdditionalInformation' />" +
            //"<Glyphs UnicodeString='Patient ID: {0}' />" +
            //"<Glyphs UnicodeString='Service date:{1}' />" +
            //"<Glyphs UnicodeString='Document Type:{2}' />" +
            //"<Glyphs UnicodeString='Echo-Provider: {3}' />" +
            //"<Glyphs UnicodeString='Procedure1: {4}' />" +
            //"<Glyphs UnicodeString='Procedure2: {5}' />" +
            //"<Glyphs UnicodeString='Note1: {6}' />" +
            //"<Glyphs UnicodeString='Note2: {7}' />" +
            //"</FixedPage>";

            if (readstatus)
            {
                str = str.Replace("{0}", clsSettings.Patient_ID);
                str = str.Replace("{1}", clsSettings.Service_Date);
                str = str.Replace("{2}", clsSettings.Document_Type);
                str = str.Replace("{3}", clsSettings.Provider_Name);
                str = str.Replace("{4}", clsSettings.Procedure_1);
                str = str.Replace("{5}", clsSettings.Procedure_2);
                str = str.Replace("{6}", clsSettings.Note_1);
                str = str.Replace("{7}", clsSettings.Note_2);
            }
            return str;
        }
        /// <summary>
        /// Used to capture endinoke of data upload process
        /// </summary>
        /// <param name="ar"></param>
        public void UploadDataCallBack(IAsyncResult ar)
        {
            try
            {
                if (ar.IsCompleted && objUploadDataDelegate != null)
                {
                    EncircleFileUpload.UploadStatus objEncircleUploadStatus =
                        objUploadDataDelegate.EndInvoke(ar);

                    objLog2 = clsCommonData.ReadLogData();
                    lstLogsuccess.Invoke(new RefreshListViewDelegate(RefreshListMethod),
                        new object[] { objLog2.lstLogData.ToArray(), objEncircleUploadStatus.Status });

                    //LoadStatusList();
                }
            }
            catch (Exception ex)
            {
                clsCommonData.WriteError(ex.Message);
            }
        }


        /// <summary>
        /// Read XPS document content Feb 21 Alagu
        /// </summary>
        /// <param name="xpsFilepath"></param>
        /// <returns></returns>
        public string readXPSDocument(string xpsFilepath)
        {
            try
            {
                //Read XPS file content
                string XPSFileContent = string.Empty;

                XpsDocument xpsDoc = new XpsDocument(xpsFilepath, FileAccess.ReadWrite, System.IO.Packaging.CompressionOption.Fast);

                //Read data using FixedDocumentSequenceReader
                IXpsFixedDocumentSequenceReader fixedDocSeqReader = xpsDoc.FixedDocumentSequenceReader;
                foreach (IXpsFixedDocumentReader docReader in fixedDocSeqReader.FixedDocuments)
                {
                    foreach (IXpsFixedPageReader fixedPageReader in docReader.FixedPages)
                    {
                        while (fixedPageReader.XmlReader.Read())
                        {
                            XPSFileContent += fixedPageReader.XmlReader.ReadOuterXml();
                            //Append Addional information
                            //string str = AppendAdditionalinfo();
                            if (isAdditionalInfoNeeded)
                                XPSFileContent += AppendAdditionalinfo();
                        }
                    }
                }
                fixedDocSeqReader = null;
                xpsDoc.Close();
                xpsDoc = null;
                return string.Format("<xml>{0}</xml>", XPSFileContent);
            }
            catch (Exception ex)
            {
                //clsCommonData.WriteError(ex.ToString());
                return string.Empty;
            }
        }
        #endregion

        /// <summary>
        /// Used to check file in use or not
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public bool FileInUse(string Path)
        {
            bool retVal = false;
            try
            {
                FileStream stream = new FileStream(Path, FileMode.Open);
                stream.Close();
                stream = null;
                return false;
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("The process cannot access the file"))
                    return true;
                else
                    return false;
            }
            return retVal;
        }
        int eventRaised = 0;

        public delegate void AddInProgressListItemDelegate(ListViewItem lvItem);
        public void AddInProgressListItem(ListViewItem lvItem)
        {
            lvInProgress.Items.Add(lvItem);            
            lvItem.Selected = true;
            lvItem.Focused = true;
            lvItem.EnsureVisible();
            lvInProgress.Focus();
            btnInProgress_Click(null, null);
            this.Update();
        }



        /// <summary>
        /// Used to handle xps file created in watching folder
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void FolderWatcher_Created(object sender, FileSystemEventArgs e)
        {           
            if (e.ChangeType != WatcherChangeTypes.Created) return;
            FileInfo fInfo = new FileInfo(e.FullPath);
            while (FileInUse(e.FullPath))
            {
                Application.DoEvents();
            }
            if (fInfo.Exists)
            {
                long size = fInfo.Length;
                fInfo = null;

                if (size > 0)
                {
                    try
                    {
                        byte[] data = null;
                        string filePath = e.FullPath;
                        string fileName = e.Name;
                        if (clsSettings.ISAdditionalInfo.ToString() == "True")
                        {
                            AdditionalInformation addinfo = new AdditionalInformation();
                            addinfo.TopLevel = true;
                            addinfo.TopMost = true;
                            addinfo.Activate();
                            addinfo.Focus();

                            switch (addinfo.ShowDialog())
                            {
                                case DialogResult.OK:
                                    isAdditionalInfoNeeded = true;
                                    break;
                                case DialogResult.Cancel:
                                    isAdditionalInfoNeeded = false;
                                    break;

                            }
                        }
                        //Step1: Read XPS Stream
                        FileStream streamXPS = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                        data = new byte[streamXPS.Length];
                        streamXPS.Read(data, 0, data.Length);
                        streamXPS.Close();
                        streamXPS = null;

                        if (data.Length < 1) return;

                        //Step2: Add In progress Item
                        ListViewItem lvItem = new ListViewItem();
                        lvItem.Text = Convert.ToString(lstLogsuccess.Items.Count + 1);
                        lvItem.SubItems.Add(clsSettings.CompanyName + "_" + clsSettings.UniqueID + "_" + e.Name);
                        lvItem.SubItems.Add(clsCommonData.STR_INPROGRESS);
                        lvItem.SubItems.Add("...");
                        lvInProgress.BeginInvoke(new AddInProgressListItemDelegate(AddInProgressListItem), lvItem);
                        
                        //Step3: Read Current Log item
                        EncircleFTM.clsLog objLogTemp = clsCommonData.ReadLogData();
                        int count = 0;
                        if (objLogTemp != null && objLogTemp.lstLogData != null)
                            count = objLogTemp.lstLogData.Count;
                        else
                            count = lstLogsuccess.Items.Count + lstLogFailed.Items.Count;
                        objLogTemp = null;
                        Application.DoEvents();

                        //Step4: Upload data to server
                        objUploadDataDelegate = new UploadDataToEncircleDelegate(UploadDataToEncircleMethod);
                        EncircleFTM.EncircleFileUpload.UploadStatus objEncircleUploadStatus =
                                UploadDataToEncircleMethod(filePath, fileName, count, 0, false, data);

                        if (objEncircleUploadStatus != null)
                        {
                            if (objEncircleUploadStatus.Message.StartsWith("FILE ERROR:"))
                            {
                                lvItem.SubItems[3].Text = "Invalid XPS File.";
                                lvItem.SubItems[2].Text = clsCommonData.STR_ERROR;
                            }
                            else
                            {
                                objLog2 = clsCommonData.ReadLogData();
                                lstLogsuccess.Invoke(new RefreshListViewDelegate(RefreshListMethod),
                                    new object[] { objLog2.lstLogData.ToArray(), objEncircleUploadStatus.Status });
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        clsCommonData.WriteError(ex.Message);
                    }
                }
            }
        }

        /// <summary>
        /// To Hide the application.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void smFileExit_Click(object sender, EventArgs e)
        {
            if (this.selSubMenuPanel != null) this.selSubMenuPanel.Visible = false;
            try
            {
                //this.isClosed=  false;
                this.Hide();
            }
            catch (Exception ex)
            {
                clsCommonData.WriteError(ex.ToString());
            }
        }

        /// <summary>
        /// To view the Remarks in the Status Strip.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuViewMessage_Click(object sender, EventArgs e)
        {
            if (this.selSubMenuPanel != null) this.selSubMenuPanel.Visible = false;
            int selIndex = -1;
            try
            {
                if (lstLogsuccess.SelectedIndices.Count < 1) return;

                selIndex = lstLogsuccess.SelectedIndices[0];

                ListViewItem selectedItem = (ListViewItem)lstLogsuccess.Items[selIndex];

                //Read remarks column data
                lblStatus.Text = selectedItem.SubItems[3].Text;
            }
            catch (Exception ex)
            {
                //write to error log
                clsCommonData.WriteError(ex.ToString());
            }
        }

        /// <summary>
        /// Navigate to the Settings Form.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void smFileSettings_Click(object sender, EventArgs e)
        {
            lblStatus.Text = "Entered Click event";
            string apppath = clsSettings.GetAppPath();
            if (this.selSubMenuPanel != null) this.selSubMenuPanel.Visible = false;
            try
            {

                Login objLogin = new Login();
                objLogin.BringToFront();
                objLogin.Activate();
                lblStatus.Text = "Login form intiated";
                StopFolderWathcher();
                switch (objLogin.ShowDialog())
                {
                    case DialogResult.OK:
                        StartFolderWathcher();
                        break;
                    case DialogResult.Cancel:
                        break;
                }
                StartFolderWathcher();
            }
            catch (Exception ex)
            {
                //write to error log
                lblStatus.Text = ex.Message.ToString();
                clsCommonData.WriteError(ex.ToString());
                MessageBox.Show(ex.InnerException.Message);
            }
        }

        /// <summary>
        /// To minimize the Application.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmStatusMonitor_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                try
                {
                    ntfStatusMonitor.Dispose();
                    ntfStatusMonitor = null;
                    this.Update();
                    e.Cancel = false;

                }
                catch (Exception ex)
                {
                    //write to error log
                    clsCommonData.WriteError(ex.ToString());
                }


            }
            catch (Exception ex)
            {
                //write to error log
                clsCommonData.WriteError(ex.ToString());
            }
        }

        /// <summary>
        /// To exit the Application.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// To activate or show the hiddded screen
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuShow_Click(object sender, EventArgs e)
        {
            this.Activate();
            this.BringToFront();
            this.Show();
        }

        /// <summary>
        /// To activate or show the hiddded screen
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuShow_Click(object sender, MouseEventArgs e)
        {
            this.Activate();
            this.BringToFront();
            this.Show();
        }

        /// <summary>
        /// To navigate to the View Error Log Form.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void smnuItemViewErrorLog_Click(object sender, EventArgs e)
        {
            if (this.selSubMenuPanel != null) this.selSubMenuPanel.Visible = false;
            try
            {
                frmViewErrorLog objViewErrorLog = new frmViewErrorLog();
                objViewErrorLog.ShowDialog();
            }
            catch (Exception ex)
            {
                //write to error log
                clsCommonData.WriteError(ex.ToString());
            }
        }

        /// <summary>
        /// To navigate to the File Transfer Log form.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void smnuItemViewFileTransfer_Click(object sender, EventArgs e)
        {
            if (this.selSubMenuPanel != null) this.selSubMenuPanel.Visible = false;
            try
            {
                frmViewFileTransferLog objViewFileTransLog = new frmViewFileTransferLog();
                objViewFileTransLog.ShowDialog();
            }
            catch (Exception ex)
            {
                //write to error log
                clsCommonData.WriteError(ex.ToString());
            }
        }

        /// <summary>
        /// To Navigate to the Help Screen.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mmHelp_Click(object sender, EventArgs e)
        {
            if (this.selSubMenuPanel != null) this.selSubMenuPanel.Visible = false;
            try
            {
                frmHelp objHelp = new frmHelp();
                objHelp.ShowDialog();
            }
            catch (Exception ex)
            {
                //write to error log
                clsCommonData.WriteError(ex.ToString());
            }
        }

        /// <summary>
        /// To navigate to the About Form.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mmAbout_Click(object sender, EventArgs e)
        {
            if (this.selSubMenuPanel != null) this.selSubMenuPanel.Visible = false;
            try
            {
                frmAbout objAbout = new frmAbout();
                objAbout.ShowDialog();
            }
            catch (Exception ex)
            {
                //write to error log
                clsCommonData.WriteError(ex.ToString());
            }
        }

        /// <summary>
        /// Resend the selected data
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuResend_Click(object sender, EventArgs e)
        {
            if (this.selSubMenuPanel != null) this.selSubMenuPanel.Visible = false;
            try
            {
                this.Update();
                if (lstLogFailed.SelectedIndices.Count > 0)
                {
                    int selIndex = lstLogFailed.SelectedIndices[0];
                    ListViewItem lvSelectedItem = (ListViewItem)lstLogFailed.Items[selIndex];

                    int recordIndex = Convert.ToInt16(lvSelectedItem.SubItems[4].Text);
                    string fileToResend = lvSelectedItem.SubItems[1].Text;
                    string filePath = System.IO.Path.Combine(clsCommonData.APP_DATA_PATH,
                        clsCommonData.STR_FOLDER_LOG_FAILED + "\\" + fileToResend);

                    ListViewItem lvInProgressItem = new ListViewItem();
                    lvInProgressItem.Text = recordIndex.ToString();
                    lvInProgressItem.SubItems.Add(fileToResend);
                    lvInProgressItem.SubItems.Add(clsCommonData.STR_INPROGRESS);
                    lvInProgressItem.SubItems.Add("Resending...");
                    lvInProgress.Items.Add(lvInProgressItem);
                    lvInProgressItem.Selected = true;
                    lvInProgressItem.Focused = true;
                    lvInProgressItem.EnsureVisible();
                    lvInProgress.Focus();
                    btnInProgress_Click(null, null);
                    //tpgInProgress.Focus();
                    //tabpage.SelectedIndex = 0;
                    this.Update();

                    byte[] data = null;
                    //Step1: Read XPS Stream
                    FileStream streamXPS = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    data = new byte[streamXPS.Length];
                    streamXPS.Read(data, 0, data.Length);
                    streamXPS.Close();
                    streamXPS = null;


                    //objUploadDataDelegate = new UploadDataToEncircleDelegate(UploadDataToEncircleMethod);
                    //objUploadDataDelegate.BeginInvoke(filePath, fileToResend, 0, recordIndex, true, null, UploadDataCallBack);
                    EncircleFTM.EncircleFileUpload.UploadStatus objEncircleUploadStatus =
                     UploadDataToEncircleMethod(filePath, fileToResend, 0, recordIndex, true, data);

                    if (objEncircleUploadStatus != null)
                    {
                        objLog2 = clsCommonData.ReadLogData();
                        lstLogsuccess.Invoke(new RefreshListViewDelegate(RefreshListMethod),
                            new object[] { objLog2.lstLogData.ToArray(), objEncircleUploadStatus.Status });
                        //LoadStatusList();
                    }
                }
            }
            catch (Exception ex)
            {
                clsCommonData.WriteError(ex.Message);
            }
        }

        /// <summary>
        /// Resend failiure files in bulk
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void smFileResend_Click(object sender, EventArgs e)
        {
            if (this.selSubMenuPanel != null) this.selSubMenuPanel.Visible = false;
            try
            {
                this.Update();

                Array checkedItems;

                foreach (ListViewItem lvSelectedItem in lstLogFailed.CheckedItems)
                {
                    int recordIndex = Convert.ToInt16(lvSelectedItem.SubItems[4].Text);
                    string fileToResend = lvSelectedItem.SubItems[1].Text;
                    string filePath = System.IO.Path.Combine(clsCommonData.APP_DATA_PATH,
                        clsCommonData.STR_FOLDER_LOG_FAILED + "\\" + fileToResend);

                    ListViewItem lvInProgressItem = new ListViewItem();
                    lvInProgressItem.Text = recordIndex.ToString();
                    lvInProgressItem.SubItems.Add(fileToResend);
                    lvInProgressItem.SubItems.Add(clsCommonData.STR_INPROGRESS);
                    lvInProgressItem.SubItems.Add("Resending...");
                    lvInProgress.Items.Add(lvInProgressItem);
                    lvInProgressItem.Selected = true;
                    lvInProgressItem.Focused = true;
                    lvInProgressItem.EnsureVisible();
                    lvInProgress.Focus();
                    btnInProgress_Click(null, null);
                    //tpgInProgress.Focus();
                    //tabpage.SelectedIndex = 0;
                    this.Update();

                    byte[] data = null;
                    //Step1: Read XPS Stream
                    FileStream streamXPS = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    data = new byte[streamXPS.Length];
                    streamXPS.Read(data, 0, data.Length);
                    streamXPS.Close();
                    streamXPS = null;

                    UploadDataToEncircleMethod(filePath, fileToResend, 0, recordIndex, true, data);
                }
                LoadStatusList();

            }
            catch (Exception ex)
            {
                clsCommonData.WriteError(ex.Message);
            }
        }

        /// <summary>
        /// Enable the in progress list
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInProgress_Click(object sender, EventArgs e)
        {
            lvInProgress.BringToFront();
            btnInProgress.BackgroundImage = EncircleFTM.Properties.Resources.btn_tab_active;
            btnSuccess.BackgroundImage = EncircleFTM.Properties.Resources.btn_tab;
            btnFailed.BackgroundImage = EncircleFTM.Properties.Resources.btn_tab;


            btnInProgress.ForeColor = Color.White;
            btnSuccess.ForeColor = Color.FromArgb(102, 102, 102);
            btnFailed.ForeColor = Color.FromArgb(102, 102, 102);

            if (this.selSubMenuPanel != null) this.selSubMenuPanel.Visible = false;
        }

        /// <summary>
        /// Enable the success list
        /// </summary>
        /// <param name="sender"></param>2
        /// <param name="e"></param>
        private void btnSuccess_Click(object sender, EventArgs e)
        {
            lstLogsuccess.BringToFront();
            btnInProgress.BackgroundImage = EncircleFTM.Properties.Resources.btn_tab;
            btnSuccess.BackgroundImage = EncircleFTM.Properties.Resources.btn_tab_active;
            btnFailed.BackgroundImage = EncircleFTM.Properties.Resources.btn_tab;

            btnInProgress.ForeColor = Color.FromArgb(102, 102, 102);
            btnSuccess.ForeColor = Color.White;
            btnFailed.ForeColor = Color.FromArgb(102, 102, 102);

            if (this.selSubMenuPanel != null) this.selSubMenuPanel.Visible = false;
        }

        /// <summary>
        /// Enable the failed list
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFailed_Click(object sender, EventArgs e)
        {
            lstLogFailed.BringToFront();
            btnInProgress.BackgroundImage = EncircleFTM.Properties.Resources.btn_tab;
            btnSuccess.BackgroundImage = EncircleFTM.Properties.Resources.btn_tab;
            btnFailed.BackgroundImage = EncircleFTM.Properties.Resources.btn_tab_active;

            btnInProgress.ForeColor = Color.FromArgb(102, 102, 102);
            btnSuccess.ForeColor = Color.FromArgb(102, 102, 102);
            btnFailed.ForeColor = Color.White;

            if (this.selSubMenuPanel != null) this.selSubMenuPanel.Visible = false;
        }

        #region "Unmaged DLL externs"
        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        //[DllImport("user32.dll", SetLastError = true)]
        //public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, IntPtr windowTitle);

        [DllImport("user32.dll")]
        static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, [MarshalAs(UnmanagedType.LPStr)] string lParam);


        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("user32.dll", SetLastError = true)]
        static extern bool PostMessage(HandleRef hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        // For Windows Mobile, replace user32.dll with coredll.dll
        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        // Find window by Caption only. Note you must pass IntPtr.Zero as the first parameter.

        [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
        static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);

        // Activate an application window.
        [DllImport("USER32.DLL")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        private const long WM_CLOSE = 0x10;
        private const uint BM_CLICK = (uint)0xf5L;
        private const long WM_KEYDOWN = 0x100;
        private const long WM_KEYUP = 0x101;
        private const long WM_CHAR = 0x102;
        private const uint WM_SETTEXT = 0xc;
        #endregion

        /// <summary>
        /// Used to set save as file dialog directory.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuSetWatchingDir_Click(object sender, EventArgs e)
        {
            try
            {
                InputDialog objInput = new InputDialog();
                switch (objInput.ShowDialog())
                {
                    case DialogResult.OK:
                        string fileName = "";
                        if (objInput.InputText.Trim().Length < 1)
                        {
                            MessageBox.Show("Please Enter print file name.", clsCommonData.STR_APPNAME);
                            return;
                        }
                        else
                        {
                            fileName = objInput.InputText.Trim();
                            if (!fileName.ToUpper().EndsWith(".XPS"))
                                fileName = string.Concat(fileName, ".xps");
                        }

                        IntPtr WindowHandle = FindWindow(null, "Save the file as");
                        IntPtr ptr = (IntPtr)0;
                        IntPtr cboBoxHandle = FindWindowEx(WindowHandle, ptr, "ComboBoxEx32", "");
                        SetForegroundWindow(cboBoxHandle);
                        IntPtr retVal = SendMessage(cboBoxHandle, WM_SETTEXT, ptr,
                            System.IO.Path.Combine(clsSettings.FolderPath + "\\" +  userName, objInput.InputText));
                        IntPtr ButtonHandle = FindWindowEx(WindowHandle, ptr, "Button", "&Save");
                        retVal = SendMessage(ButtonHandle, BM_CLICK, ptr, "0");
                        break;
                    case DialogResult.Cancel:
                        MessageBox.Show("Please Enter print file name.", clsCommonData.STR_APPNAME);
                        break;
                }
            }
            catch (Exception ex)
            {
            }
        }


        #region "Custom Menu Events"
        Panel selSubMenuPanel = null;

        private void InitializeCustomMenu()
        {
            //Initialize main menu events
            btnFile.Click += new EventHandler(btnFile_Click);
            btnView.Click += new EventHandler(btnView_Click);

            btnFile.MouseEnter += new EventHandler(mainmenu_MouseEnter);
            btnFile.MouseLeave += new EventHandler(mainmenu_MouseLeave);

            btnView.MouseEnter += new EventHandler(mainmenu_MouseEnter);
            btnView.MouseLeave += new EventHandler(mainmenu_MouseLeave);

            btnHelp.MouseEnter += new EventHandler(mainmenu_MouseEnter);
            btnHelp.MouseLeave += new EventHandler(mainmenu_MouseLeave);

            btnAbout.MouseEnter += new EventHandler(mainmenu_MouseEnter);
            btnAbout.MouseLeave += new EventHandler(mainmenu_MouseLeave);

            //Initialize sub menu items
            //File Submenu
            btnResend.MouseEnter += new EventHandler(submenu_MouseEnter);
            btnResend.MouseLeave += new EventHandler(submenu_MouseLeave);
            //btnResend.LostFocus += new EventHandler(btnResend_LostFocus);

            btnSettings.MouseEnter += new EventHandler(submenu_MouseEnter);
            btnSettings.MouseLeave += new EventHandler(submenu_MouseLeave);
            //btnSettings.LostFocus += new EventHandler(btnResend_LostFocus);

            btnCloseMenu.MouseEnter += new EventHandler(submenu_MouseEnter);
            btnCloseMenu.MouseLeave += new EventHandler(submenu_MouseLeave);
            //btnCloseMenu.LostFocus += new EventHandler(btnResend_LostFocus);

            //View Submenu
            btnViewErrorLog.MouseEnter += new EventHandler(submenu_MouseEnter);
            btnViewErrorLog.MouseLeave += new EventHandler(submenu_MouseLeave);
            //btnViewErrorLog.LostFocus += new EventHandler(btnResend_LostFocus);

            btnViewFileTransLog.MouseEnter += new EventHandler(submenu_MouseEnter);
            btnViewFileTransLog.MouseLeave += new EventHandler(submenu_MouseLeave);
            //btnViewFileTransLog.LostFocus += new EventHandler(btnResend_LostFocus);

            pnlFileSubmenu.Parent.Click += new EventHandler(Parent_Click);
            pnlViewSubMenu.Parent.Click += new EventHandler(Parent_Click);
        }

        /// <summary>
        /// disable active submenu items
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnResend_LostFocus(object sender, EventArgs e)
        {
            if (this.selSubMenuPanel != null) this.selSubMenuPanel.Visible = false;
        }

        void Parent_Click(object sender, EventArgs e)
        {
            if (this.selSubMenuPanel != null) this.selSubMenuPanel.Visible = false;
        }

        /// <summary>
        /// Populate file submenu items
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnFile_Click(object sender, EventArgs e)
        {
            Button selMenu = (Button)sender;
            pnlFileSubmenu.Visible = true;
            pnlFileSubmenu.Left = selMenu.Left;
            pnlFileSubmenu.Top = selMenu.Parent.Top + selMenu.Parent.Height;
            this.selSubMenuPanel = pnlFileSubmenu;
            this.selSubMenuPanel.Tag = ((Button)sender).Text;
            this.selSubMenuPanel.BringToFront();
            btnResend.Focus();
        }

        /// <summary>
        /// Populate file submenu items
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnView_Click(object sender, EventArgs e)
        {
            Button selMenu = (Button)sender;
            pnlViewSubMenu.Visible = true;
            pnlViewSubMenu.Left = selMenu.Left;
            pnlViewSubMenu.Top = selMenu.Parent.Top + selMenu.Parent.Height;
            this.selSubMenuPanel = pnlViewSubMenu;
            this.selSubMenuPanel.Tag = ((Button)sender).Text;
            this.selSubMenuPanel.BringToFront();
            btnViewErrorLog.Focus();
        }

        private void mainmenu_MouseEnter(object sender, EventArgs e)
        {
            Button selectedLbl = (Button)sender;
            selectedLbl.BackColor = Color.FromArgb(156, 156, 156);
            selectedLbl.ForeColor = Color.Gainsboro;
            selectedLbl.Cursor = Cursors.Hand;
            if (selSubMenuPanel != null && selSubMenuPanel.Tag.ToString() != selectedLbl.Name)
            {
                selSubMenuPanel.Visible = false;
                selSubMenuPanel = null;
            }
        }

        private void mainmenu_MouseLeave(object sender, EventArgs e)
        {
            Button selectedLbl = (Button)sender;
            selectedLbl.BackColor = Color.Transparent;
            selectedLbl.ForeColor = Color.Gainsboro;
            selectedLbl.Cursor = Cursors.Arrow;
        }

        private void submenu_MouseEnter(object sender, EventArgs e)
        {
            Button selectedLbl = (Button)sender;
            selectedLbl.BackColor = Color.FromArgb(113, 113, 113);
            selectedLbl.ForeColor = Color.Gainsboro;
            selectedLbl.Cursor = Cursors.Hand;
        }

        private void submenu_MouseLeave(object sender, EventArgs e)
        {
            Button selectedLbl = (Button)sender;
            selectedLbl.BackColor = Color.FromArgb(117, 117, 117);
            selectedLbl.ForeColor = Color.Gainsboro;
            selectedLbl.Cursor = Cursors.Arrow;
        }

        /// <summary>
        /// Dispose active submenu items
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panel1_Click(object sender, EventArgs e)
        {
            if (this.selSubMenuPanel != null) this.selSubMenuPanel.Visible = false;
        }
        #endregion

        private void lblStatus_MouseClick(object sender, MouseEventArgs e)
        {
            lblStatus.Text = clsSettings.GetAppPath();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            AdditionalInformation objadd = new AdditionalInformation();
            objadd.Activate();
            objadd.Show();
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            //AdditionalInfoPopup sdf = new AdditionalInfoPopup();
            //sdf.Activate();
            //sdf.Show();
        }
    }
}


